import { app, shell, BrowserWindow, ipcMain, dialog, desktopCapturer } from 'electron'
import { join } from 'path'
import { createRequire } from 'module'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import fs from 'fs'
let mainWindow = null
let writeStream = null
let recordingStartTime = null
// 读取配置文件
function getConfig() {
  const require = createRequire(import.meta.url)
  let configPath
  if (is.dev) {
    // 开发环境：从项目根目录读取
    configPath = join(__dirname, '../../resources/config.json')
  } else {
    // 生产环境：从 resources 目录读取（已配置 asarUnpack，可修改）
    // 尝试多个可能的路径
    const possiblePaths = [
      join(process.resourcesPath, 'config.json'), // 标准路径
      join(process.resourcesPath, 'resources/config.json'), // 如果 resources 在子目录
      join(app.getAppPath(), 'resources/config.json') // 备用路径
    ]
    // 找到第一个存在的路径
    const fs = require('fs')
    for (const path of possiblePaths) {
      if (fs.existsSync(path)) {
        configPath = path
        break
      }
    }

    // 如果都没找到，使用默认路径
    if (!configPath) {
      configPath = possiblePaths[0]
    }
  }

  try {
    return require(configPath)
  } catch (error) {
    console.error('读取配置文件失败:', error)
    console.error('配置文件路径:', configPath)
    // 返回默认配置
    return { url: 'https://www.baidu.com' }
  }
}
// 显示退出确认对话框
async function showExitConfirmation(mainWindow, isConfirmingExit) {
  if (!mainWindow || isConfirmingExit) return
  isConfirmingExit = true // 设置标志，防止重复触发
  try {
    const { response } = await dialog.showMessageBox(mainWindow, {
      type: 'question',
      buttons: ['确认', '取消'],
      defaultId: 1, // 默认选中"取消"
      cancelId: 1, // 按 ESC 或点击取消时返回 1
      title: '退出确认',
      message: '确定要退出程序吗？',
      detail: '点击"确认"将关闭应用程序。'
    })

    // 点击了确认
    if (response === 0) {
      app.quit()
    }
  } catch (error) {
    console.error('显示确认对话框时出错:', error)
  } finally {
    setTimeout(() => {
      isConfirmingExit = false
    }, 300) // 延迟一点时间，避免快速连续按键
  }
}
// 停止正在进行的录制
function stopRecordingIfActive() {
  if (writeStream) {
    writeStream.end()
    writeStream = null
  }
}

function createWindow() {
  let isConfirmingExit = false
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    frame: true,
    fullscreen: true,
    fullscreenable: true,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: true,
      nodeIntegration: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })
  mainWindow.on('closed', () => {
    stopRecordingIfActive()
    mainWindow = null
  })
  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  // 开启调试
  if (is.dev) {
    mainWindow.webContents.openDevTools()
  }
  // 读取配置文件中的 URL
  const config = getConfig()
  const targetUrl = config.url || 'https://www.baidu.com'

  // 确保 URL 包含协议
  const url =
    targetUrl.startsWith('http://') || targetUrl.startsWith('https://')
      ? targetUrl
      : `https://${targetUrl}`

  // HMR for renderer base on electron-vite cli.
  // 在开发环境中，优先使用 ELECTRON_RENDERER_URL（如果存在）
  // 否则使用配置文件中的 URL
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(url)
  } else {
    // 加载配置文件中的 URL
    mainWindow.loadURL(url)
  }
  // 监听键盘输入事件，捕获 Esc 键
  mainWindow.webContents.on('before-input-event', (event, input) => {
    if (input.key === 'Escape' && !isConfirmingExit) {
      event.preventDefault() // 阻止默认行为
      showExitConfirmation(mainWindow, isConfirmingExit)
    }
  })
}
app.whenReady().then(() => {
  // 获取当前窗口信息
  ipcMain.handle('get-current-window-info', async (event) => {
    try {
      const window = BrowserWindow.fromWebContents(event.sender)
      if (!window) {
        return { success: false, error: '无法获取当前窗口' }
      }

      return {
        success: true,
        title: window.getTitle(),
        id: window.id
      }
    } catch (error) {
      const err = error
      return { success: false, error: err.message }
    }
  })

  // 获取可用的屏幕/窗口源
  ipcMain.handle('get-video-sources', async (event) => {
    try {
      const sources = await desktopCapturer.getSources({
        types: ['window'], // 仅获取窗口源
        thumbnailSize: { width: 150, height: 150 }, // 设置窗口缩略图的大小
        fetchWindowIcons: true // 获取窗口图标信息
      })

      // 获取当前窗口信息以便匹配
      const currentWindow = BrowserWindow.fromWebContents(event.sender)
      const currentWindowTitle = currentWindow?.getTitle() || ''

      // 过滤掉系统窗口和不可见的窗口
      const filteredSources = sources.filter((source) => {
        // 排除一些系统窗口和屏幕源
        const excludedNames = ['Entire Screen', 'Screen 1', 'Screen 2']
        if (excludedNames.some((name) => source.name.includes(name))) {
          return false
        }
        return true
      })

      console.log('当前窗口标题:', currentWindowTitle)
      console.log('可用源数量:', filteredSources.length)
      console.log(
        '可用源列表:',
        filteredSources.map((s) => ({ id: s.id, name: s.name }))
      )

      return {
        success: true,
        sources: filteredSources,
        currentWindowTitle: currentWindowTitle
      }
    } catch (error) {
      const err = error
      console.error('获取视频源错误:', err)
      return { success: false, error: err.message }
    }
  })
  // 开始录制 - 在渲染进程中处理媒体流，主进程只负责文件写入
  ipcMain.handle('start-recording', async (_event, _options) => {
    try {
      const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
        defaultPath: `课程录制-${new Date().toISOString().replace(/[:.]/g, '-')}.webm`,
        filters: [
          { name: '视频文件', extensions: ['webm', 'mp4'] },
          { name: '所有文件', extensions: ['*'] }
        ]
      })

      if (canceled) {
        return { success: false, error: '用户取消了保存' }
      }

      // 创建文件写入流
      if (!filePath) {
        return { success: false, error: '文件路径无效' }
      }
      writeStream = fs.createWriteStream(filePath)
      recordingStartTime = Date.now()

      return {
        success: true,
        message: '准备开始录制',
        filePath: filePath
      }
    } catch (error) {
      const err = error
      return { success: false, error: err.message }
    }
  })
  // 接收录制的数据块并写入文件
  ipcMain.on('recording-data', (event, data) => {
    if (writeStream && !writeStream.destroyed) {
      try {
        const buffer = Buffer.from(data)
        writeStream.write(buffer)
        // 发送录制进度
        if (recordingStartTime) {
          const duration = Date.now() - recordingStartTime
          event.sender.send('recording-progress', {
            duration: Math.floor(duration / 1000),
            fileSize: writeStream.bytesWritten
          })
        }
      } catch (error) {
        const err = error
        event.sender.send('recording-error', `写入错误: ${err.message}`)
      }
    }
  })
  // 停止录制并保存文件
  ipcMain.handle('stop-recording', async () => {
    try {
      if (writeStream) {
        const filePath = writeStream.path
        writeStream.end()
        await new Promise((resolve) => writeStream.on('close', resolve))

        const stats = fs.statSync(filePath)
        const duration = recordingStartTime
          ? Math.floor((Date.now() - recordingStartTime) / 1000)
          : 0

        const result = {
          success: true,
          message: '录制已保存',
          filePath: filePath,
          duration: duration,
          fileSize: stats.size
        }

        writeStream = null
        recordingStartTime = null

        return result
      }
      return { success: false, error: '没有正在进行的录制' }
    } catch (error) {
      const err = error
      return { success: false, error: err.message }
    }
  })
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  // IPC test
  ipcMain.on('ping', () => console.log('pong'))
  createWindow()
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    stopRecordingIfActive()
    app.quit()
  }
})
app.on('before-quit', () => {
  stopRecordingIfActive()
})
// 防止多次启动
if (!app.requestSingleInstanceLock()) {
  app.quit()
} else {
  app.on('second-instance', () => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })
}
